<script setup>
import { ElMessage } from 'element-plus';
import { useProductApi } from '/@/api/product';
import { isEmpty, isStr } from '/@/utils';

const { addParam, getParamList } = useProductApi();

const props = defineProps({
	modelValue: {
		type: Object,
		default: () => {
			return {};
		},
	},
});
const emit = defineEmits(['update:modelValue']);
const selectedId = computed({
	get() {
		return props.modelValue.attributeId;
		// return props.modelValue.id || props.modelValue.name || "";
		// console.log(props.modelValue);
		// return props.modelValue || {};
	},
	set() {},
});
const options = ref([]);
const loading = ref(false);
//远程搜索
async function remoteMethod(query) {
	try {
		let params = {
			current: 1,
			pageSize: 99,
			status: null,
			name: query === ' ' ? null : query,
		};
		loading.value = true;
		let res = await getParamList(params);
		loading.value = false;
		if (res.code !== 200) return;
		options.value = res.data.data.data.map((item) => {
			item.attributeId = item.id;
			item.attributeName = item.name;
			delete item.id;
			return item;
		});
		console.log(options.value);
	} catch (error) {
		loading.value = false;
	}
}
onMounted(() => {
	remoteMethod('');
});
//更改选项时
function change(val) {
	console.log('val:' + val);
	if (isEmpty(val)) return;
	if (isStr(val)) {
		addParamItem(val);
	} else {
		const selectedItem = options.value.find(({ attributeId }) => attributeId === val);
		emit('update:modelValue', selectedItem);
	}
}
async function addParamItem(name) {
	loading.value = true;
	let res = await addParam({
		name,
		status: 1,
	});
	loading.value = false;
	if (res.code !== 200) return;
	ElMessage.success('新参数名创建成功！');
}
</script>
<template>
	<div class="ParamsSelector">
		<el-select
			v-model="selectedId"
			filterable
			remote
			reserve-keyword
			allow-create
			default-first-option
			placeholder="请输入关键词"
			:remote-method="remoteMethod"
			:loading="loading"
			clearable
			@change="change"
		>
			<el-option v-for="item in options" :key="item.attributeId" :label="item.attributeName" :value="item.attributeId"> </el-option>
		</el-select>
	</div>
</template>
